#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import urllib2
import lxml.html as htm
import lxml.html.soupparser as soup # Note: internally imports BeautifulSoup
import time

log = logging.getLogger()

POST_URL="http://info.russianpost.ru/servlet/post_item?action=search&searchType=barCode&show_form=no&barCode=%s&page=1" # Track No as parameter
TRACK_FILE="tracks.txt"
HTML_FILE="index.html"

def main():
    out = [] # output links
    tracks = [x.strip() for x in open(TRACK_FILE,'Ur').readlines() if x.strip()]

    for trk in tracks:
        log.debug(u"Check tracking #%s" % (trk,))

        try:
            f = urllib2.urlopen(POST_URL % trk)
        except:
            log.exception(u"Get info for `%s` failed (open url)" % trk)

        try:
            s = f.read()
            f.close()
        except:
            log.exception(u"Get info for `%s` failed (read)" % trk)

        try:
            try:
                x = htm.document_fromstring(s)
            except: # broken html fallback
                x = soup.fromstring(s)

            tbl = x.xpath('/html/body/table[1]')
            log.debug(u"TBL: %s" % (tbl,))

            if tbl:
                s = ''
                tr = tbl[0].xpath('tr')[-2].xpath('td')
                out.append((trk, u"%s: %s (%s %s)" % (tr[1].text, tr[0].text, tr[3].text, tr[4].text)))
            else:
                out.append((trk, 'No information available'))

        except:
            log.exception(u"")

    # make output
    ht = [u"<html>",
           u"<head><meta http-equiv='content-type' content='text/html;charset=utf-8'/></head>",
           u"<body>"
           u"<h2>Tracking info</h2>",
           u"<h4>Last update: %s" % time.asctime(),
           u"<h5>Add track numbers into `tracks.txt`</h5>"]

    for s in out:
        ht.append(
            u"<a href='%s'>%s</a>: %s" % (POST_URL % s[0], s[0],s[1])
        )

    ht.append(u"</body></html>")

    with open(HTML_FILE, "w") as f:
        print >>f , "\n".join(ht).encode('utf-8')

    log.debug('Done.')

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)

    main()